﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MiddleServices
{
    public class AutoThreadWork
    {
        private bool blnWork = false;

        private Thread thread;

        public AutoThreadWork()
        {
        }

        public bool ServerIsWork
        {
            get
            {
                return blnWork;
            }
        }

        /// <summary>
        /// 开启线程
        /// </summary>
        public void Start()
        {
            blnWork = true;

            thread = new Thread(new ThreadStart(ThreadWork));

            thread.IsBackground = true;

            thread.Start();

            LogManager.Write2TXT("启动");
        }

        /// <summary>
        /// 关闭线程
        /// </summary>
        public void Stop()
        {
            blnWork = false;

            try
            {
                //thread.Abort(); 这是立即停止
            }
            catch { }

            LogManager.Write2TXT("停止");
        }

        /// <summary>
        /// 线程工作方法
        /// </summary>
        private void ThreadWork()
        {
            try
            {
                while (blnWork)
                {
                    try
                    {
                        //写你的业务逻辑
                    }
                    catch (Exception ex)
                    {
                        LogManager.Write2TXT("业务逻辑出错" + ex.Message);


                    };

                    Thread.Sleep(5000);
                }
            }
            catch { };
        }
    }
}
